﻿using Engine;
using Engine.Graphics;

namespace Game
{
    public class TestLensCamera : FppCamera
    {
        public float FocalNum;

        public bool IsFocalControllable;

        public bool IsItemVisible;

        public override bool IsEntityControlEnabled => true;

        public override Matrix ProjectionMatrix
        {
            get
            {
                if (!m_projectionMatrix.HasValue)
                {
                    m_projectionMatrix = CalculateBaseProjectionMatrix(base.GameWidget.ViewWidget.ActualSize);
                    ViewWidget viewWidget = base.GameWidget.ViewWidget;
                    if (!viewWidget.ScalingRenderTargetSize.HasValue)
                    {
                        m_projectionMatrix *= CreateScaleTranslation(0.5f * viewWidget.ActualSize.X, -0.5f * viewWidget.ActualSize.Y, viewWidget.ActualSize.X / 2f, viewWidget.ActualSize.Y / 2f) * viewWidget.GlobalTransform * CreateScaleTranslation(2f / (float)Display.Viewport.Width, -2f / (float)Display.Viewport.Height, -1f, 1f);
                    }
                }

                return m_projectionMatrix.Value;
            }
        }

        public TestLensCamera(GameWidget view)
            : base(view)
        {
            IsFocalControllable = false;
            IsItemVisible = false;
            FocalNum = 4f;
        }

        public Matrix CalculateBaseProjectionMatrix(Vector2 wh)
        {
            float num = 90f;
            float num2 = 1f;
            if (SettingsManager.ViewAngleMode == ViewAngleMode.Narrow)
            {
                num2 = 0.8f;
            }
            else if (SettingsManager.ViewAngleMode == ViewAngleMode.Normal)
            {
                num2 = 0.9f;
            }

            float num3 = num2 / FocalNum;
            float num4 = wh.X / wh.Y;
            float num5 = MathUtils.Min(num * num4, num);
            float num6 = num5 * num4;
            if (num6 < 90f)
            {
                num5 *= 90f / num6;
            }
            else if (num6 > 175f)
            {
                num5 *= 175f / num6;
            }

            return Matrix.CreatePerspectiveFieldOfView(MathUtils.DegToRad(num5 * num3), num4, 0.1f, 2048f);
        }

        public static Matrix CreateScaleTranslation(float sx, float sy, float tx, float ty)
        {
            return new Matrix(sx, 0f, 0f, 0f, 0f, sy, 0f, 0f, 0f, 0f, 1f, 0f, tx, ty, 0f, 1f);
        }
    }
}